﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DTO;

namespace IndexMarkWcfService.Caches
{
    public class DepartmentTreeCache: CacheInvokerBase
    {
        private static Dictionary<int, IEnumerable<Department>> _cacheDictionary = new Dictionary<int, IEnumerable<Department>>();

        public DepartmentTreeCache()
        {

        }

        public override object[] AllocateInputs()
        {
            return BaseInvoker.AllocateInputs();
        }

        public override object Invoke(object instance, object[] inputs, out object[] outputs)
        {
            IEnumerable<Department> result = new List<Department>();
            int invokeInputParam = (int)inputs[0];

            if (_cacheDictionary.ContainsKey(invokeInputParam) == true)
            {
                result = _cacheDictionary[invokeInputParam];
            }
            else
            {
                result = BaseInvoker.Invoke(instance, inputs, out outputs) as IEnumerable<Department>;
                try
                {
                    _cacheDictionary.Add(invokeInputParam, result);
                }
                catch
                {
                    _cacheDictionary.Remove(invokeInputParam);
                    _cacheDictionary.Add(invokeInputParam, result);
                }
            }

            outputs = new object[] { };
            return result;
        }

        public override IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
        {
            return BaseInvoker.InvokeBegin(instance, inputs, callback, state);
        }

        public override object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
        {
            return BaseInvoker.InvokeEnd(instance, out outputs, result);
        }

        public override bool IsSynchronous
        {
            get { return true; }
        }

        public static void Clear()
        {
            _cacheDictionary.Clear();
        }
    }
}
